﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class UploadController : Base
    {
        private readonly ConfigService configService;
        private readonly AttmentService _attment;
        private readonly LoginUtil _LoginUtil;
        public UploadController(ConfigService config, AttmentService attmentService, LoginUtil LoginUtil)
        {
            configService = config;
            _attment = attmentService;
            _LoginUtil = LoginUtil;
        }


        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.Upload_Upload)]
        public async Task<IActionResult> Upload(IFormFile file, string source, string type = "")
        {
            ViewUploadInfo uploadInfo = new()
            {
                Success = false
            };

            long size = file.Length;       //统计文件大小

            if (size < 0 || size == 0)        //文件大小 0 才上传
            {
                uploadInfo.Error = "上传文件不存在！";
                return Json(uploadInfo);
            }

            string fileName = file.FileName;

            SytemConfig configSiteInfo = await configService.GetByNameAsync();
            string baseDir = configSiteInfo.BaseDir;

            //图片限制信息
            string[] imgageExts = configSiteInfo.ImageExt.Split(',');
            int imageSize = configSiteInfo.ImageSize * 1024;

            //文件限制信息
            string[] fileExts = configSiteInfo.FileExt.Split(',');
            int fileSize = configSiteInfo.FileSize * 1024;

            string fileExt = Path.GetExtension(fileName).ToLower();//文件后缀
            string uploadDir;

            if (((IList)imgageExts).Contains(fileExt))
            {
                if (!imgageExts.Any(m => m.Equals(fileExt, StringComparison.OrdinalIgnoreCase)))
                {
                    uploadInfo.Error = "上传图片类型不合法！";
                    return Json(uploadInfo);
                }
                if (size > imageSize)
                {
                    uploadInfo.Error = "上传文件超过系统大小限制！";
                    return Json(uploadInfo);
                }
                uploadDir = configSiteInfo.ImageDir ?? "Images";
            }
            else if (((IList)fileExts).Contains(fileExt))
            {
                if (!fileExts.Any(m => m.Equals(fileExt, StringComparison.OrdinalIgnoreCase)))
                {
                    uploadInfo.Error = "上传文件类型不合法！";
                    return Json(uploadInfo);
                }
                if (size > fileSize)
                {
                    uploadInfo.Error = "上传文件超过系统大小限制！";
                    return Json(uploadInfo);
                }
                uploadDir = configSiteInfo.FileDir ?? "Files";
            }
            else
            {
                uploadInfo.Error = "非法上传！";
                return Json(uploadInfo);
            }
            if (source == "Notice")
                uploadDir = configSiteInfo.NoticeAttDir ?? "Notice";

            if (source == "User")
                uploadDir = "User";

            string dateDir = DateTime.Now.ToString("yyyyMM");

            var dirPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", baseDir, uploadDir, dateDir);

            if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);//如目录不存在，则以当前日期创新目录

            string newFileName = MD5Utility.MD5Encrypt16(fileName + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff:ffffff")).ToLower(); //获取当前时间微秒 生成MD5
            string saveFilePath = Path.Combine(dirPath, newFileName + fileExt); //当前上传文件应存放的位置 path.combine 内置跨平台文件系统路径拼接方法
            using var stream = System.IO.File.Create(saveFilePath);
            try
            {
                await file.CopyToAsync(stream);     //上传文件
                uploadInfo.Success = true;
                uploadInfo.Filename = fileName;
                uploadInfo.Ext = fileExt;
                uploadInfo.Url = "/" + baseDir + "/" + uploadDir + "/" + dateDir + "/" + newFileName + fileExt;

                int userId = await _LoginUtil.LoginUserId();

                Attment attment = new()
                {
                    Filename = fileName,
                    Ext = fileExt,
                    Url = uploadInfo.Url,
                    Size = size / 1024,
                    Source = source,
                    Uid = userId,
                    Time = DateTime.Now
                };
                object attId = await _attment.InsertAsync(attment);

                return type switch
                {
                    "Tinymce" => Json(new { location = uploadInfo.Url, status = 200 }),
                    "layui" => Json(new { data = uploadInfo, status = 1, pkey = attId, info = "上传成功" }),
                    "layuiImg" => Json(new { data = uploadInfo, status = 1, info = "上传成功" }),
                    _ => Json(uploadInfo),
                };
            }
            catch (Exception ex)        //上传异常处理
            {
                uploadInfo.Success = false;
                uploadInfo.Error = ex.ToString();
                return Json(uploadInfo);
            }
        }

    }

}
